<?php
namespace app\jobs;

use addons\faqueue\model\FaqueueLog;
use app\api\service\PromoteService;
use think\Log;
use think\queue\Job;

class NormalPromoteJob
{

    public function fire(Job $job, $data)
    {
        // 处理任务逻辑
        $attemptsnum = $job->attempts();

        $isSuccess = $this->processData($data,$attemptsnum);

        if ($isSuccess) {
            $job->delete(); // 任务成功，删除任务
            Log::write($job->getName()."执行成功：".print_r($data,true),'info');
            (new FaqueueLog())->log($job->getQueue(),$job->getName(),$data);

        } else {
            if ($job->attempts() > 5) { // 最多重试5次
                Log::write($job->getName()."执行失败，已重试5次，任务删除， 数据：".print_r($data,true),'error');
                $job->delete();
            } else {
                Log::write($job->getName()."重试中，10秒后重试 数据：".print_r($data,true),'error');
                $job->release(5); // 5秒后重试
            }
        }
    }

    // 任务失败处理
    public function failed($data)
    {
        // 记录失败日志或发送通知
        Log::error("任务失败: " . json_encode($data));
    }

    private function processData($data,$attemptsnum)
    {
        try {
            if ($attemptsnum > 5) {
                return false;
            }
            PromoteService::getInstance()->normalPromote($data['order_id']);
            return true;

        }catch (\Exception $e){
            Log::error("NormalPromoteJob 执行出现错误：".print_r($e->getMessage(),true));
            return  false;
        }

    }
}